﻿using CNFM_CROCODILE_LOGO.Core.Domain.Current;
using CNFM_CROCODILE_LOGO.Core.Domain.Entity;
using CNFM_CROCODILE_LOGO.Core.Domain.ViewModels;
using CNFM_CROCODILE_LOGO.Core.Repository;
using CNFM_CROCODILE_LOGO.Data.RestClient;
using CNFM_CROCODILE_LOGO.RestClient.Domain;
using CNFM_CROCODILE_LOGO.RestClient.Utils;
using CNFM_CROCODILE_LOGO.Services.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CNFM_CROCODILE_LOGO.Services.Implementations
{
    /// <summary>
    /// 基础管理接口实现
    /// </summary>
    public class BasicServices : IBasicServices
    {
        private IEfRepository _rep;
        public BasicServices(IEfRepository rep)
        {
            this._rep = rep;
        }

        #region 用户管理
        /// <summary>
        /// 用户停用
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ReturnValueModel DelectCrocodileUser(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = "用户Id,不能为空!" };
            var userList = _rep.Where<CrocodileUser>(p => p.Status == 0 && p.Id == userId).ToList();
            if (userList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该用户,请确认用户是否为可用状态!" };

            var userItem = userList.FirstOrDefault();
            userItem.Status = -1;
            _rep.Update(userItem);

            return new ReturnValueModel { Code = 200, Msg = "success" };
        }

        /// <summary>
        /// 用户新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateCrocodileUser(CrocodileUserModels model)
        {

            if (string.IsNullOrEmpty(model.Id))
            {
                List<string> mgsList = new List<string>();
                mgsList.Add((string.IsNullOrEmpty(model.LoginName) ? "账户" : null));
                mgsList.Add((string.IsNullOrEmpty(model.UserName) ? "用户名" : null));
                foreach (var item in mgsList)
                    if (!string.IsNullOrEmpty(item))
                        return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

                if (_rep.Where<CrocodileUser>(p => p.Status == 0 && p.LoginName == model.LoginName).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "该账户已被注册!" };

                if (_rep.Where<CrocodileUser>(p => p.Status == 0 && p.TelePhone == model.TelePhone).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "该手机号已被注册!" };

                //UserAdd
                CrocodileUser crocodileUser = new CrocodileUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    LoginName = model.LoginName,
                    Password = string.IsNullOrEmpty(model.Password) ? UtilsHelp.GetMD5("123456") : UtilsHelp.GetMD5(model.Password),
                    UserName = model.UserName,
                    TelePhone = model.TelePhone,
                    UnCode = model.UnCode,
                    CompanyName = model.CompanyName,
                    Email = model.Email,
                    RoleId = model.RoleId,
                    Remarks = model.Remarks
                };

                _rep.Insert(crocodileUser);

                return new ReturnValueModel { Code = 200, Msg = "success!" };
            }

            var userList = _rep.Where<CrocodileUser>(p => p.Status == 0 && p.Id == model.Id).ToList();
            if (userList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该用户,请确认用户是否为可用状态!" };

            if (userList.Where(p => p.Status == 0 && p.TelePhone == model.TelePhone && p.Id != model.Id).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "该手机号已被注册!" };

            var userItem = userList.FirstOrDefault();
            userItem.UserName = string.IsNullOrEmpty(model.UserName) ? userItem.UserName : model.UserName;
            userItem.TelePhone = string.IsNullOrEmpty(model.TelePhone) ? userItem.TelePhone : model.TelePhone;
            userItem.UnCode = string.IsNullOrEmpty(model.UnCode) ? userItem.UnCode : model.UnCode;
            userItem.CompanyName = string.IsNullOrEmpty(model.CompanyName) ? userItem.CompanyName : model.CompanyName;
            userItem.Email = string.IsNullOrEmpty(model.Email) ? userItem.Email : model.Email;
            userItem.Remarks = string.IsNullOrEmpty(model.Remarks) ? userItem.Remarks : model.Remarks;

            _rep.Update(userItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 企业开户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddEnterprise(CrocodileUserModels model)
        {
            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.LoginName) ? "账户" : null));
            mgsList.Add((string.IsNullOrEmpty(model.UserName) ? "企业名称" : null));
            mgsList.Add((string.IsNullOrEmpty(model.UnCode) ? "地区" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            if (_rep.Where<CrocodileUser>(p => p.Status == 0 && p.LoginName == model.LoginName).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "该账户已被注册!" };

            if (_rep.Where<Enterprise>(p => p.Status == 0 && p.EnterpriseName == model.UserName && p.UnCode == model.UnCode).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "该企业已存在!" };

            var roleId = _rep.FirstOrDefault<Role>(p => p.RoleName == "企业用户").Id;

            //1.创建账户
            CrocodileUser crocodileUser = new CrocodileUser()
            {
                Id = Guid.NewGuid().ToString(),
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = UserBasic.UserId(),
                LoginName = model.LoginName,
                Password = string.IsNullOrEmpty(model.Password) ? UtilsHelp.GetMD5("123456") : UtilsHelp.GetMD5(model.Password),
                UserName = model.UserName,
                UnCode = model.UnCode,
                RoleId = roleId,
                EnterpriseId = Guid.NewGuid().ToString(),
                Remarks = model.Remarks
            };

            _rep.Insert(crocodileUser);
            //2.创建企业

            Enterprise enterprise = new Enterprise()
            {
                Id = crocodileUser.EnterpriseId,
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = UserBasic.UserId(),
                EnterpriseName = model.UserName,
                UnCode = model.UnCode,
                RegisteredTime = DateTime.Now
            };

            _rep.Insert(enterprise);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ReturnValueModel GetCrocodileUser(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = "用户Id,不能为空!" };
            var userList = _rep.Where<CrocodileUser>(p => p.Status == 0 && p.Id == userId).ToList();
            if (userList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该用户,请确认用户是否为可用状态!" };

            var model = userList.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="areUnCode">地区编码</param>
        /// <param name="type">用户类型</param>
        /// <param name="sasearch">模糊条件</param>
        /// <returns></returns>
        public PaginationModel GetCrocodileUserAll(int index, int size, string areUnCode, string type, string sasearch)
        {


            //地区数据
            var sql1 = string.Empty;
            List<string> arrt3 = new List<string>();
            string[] arrt4;
            if (!string.IsNullOrEmpty(areUnCode) && areUnCode != "undefined" && areUnCode != "null")
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, areUnCode).ToList();

                foreach (var item in areaAll)
                    arrt3.Add(item.YUnCode);
                arrt4 = arrt3.ToArray();
            }
            else
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE PUnCode={0}  AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, 0).ToList();

                foreach (var item in areaAll)
                    arrt3.Add(item.YUnCode);
                arrt4 = arrt3.ToArray();
            }

            var userList = from a in _rep.Where<CrocodileUser>(p => p.Status == 0)
                           where !string.IsNullOrEmpty(areUnCode) && areUnCode != "undefined" && areUnCode != "null"
                           ? arrt4.Contains(a.UnCode) : a.Status == 0
                           join e in _rep.Where<Area>(p => true) on a.UnCode equals e.YUnCode into e
                           from ei in e.DefaultIfEmpty()
                           join r in _rep.Where<Role>(p => true) on a.RoleId equals r.Id into r
                           from ri in r.DefaultIfEmpty()
                           select new
                           {
                               a.Id,
                               a.LoginName,
                               a.UserName,
                               a.TelePhone,
                               ei.AreaName,
                               a.CompanyName,
                               a.Email,
                               TypeName = ri.RoleName,
                               a.Status,
                               a.CreateTime,
                               a.CreateId
                           };


            var userAll = userList.OrderByDescending(p => p.CreateTime)
                .WhereIf(p => p.UserName.Contains(sasearch) || p.TelePhone.Contains(sasearch)
                || p.CompanyName.Contains(sasearch) || p.AreaName.Contains(sasearch) || p.TypeName.Contains(sasearch),
                string.IsNullOrEmpty(sasearch) == false);

            var total = userAll.Count();
            var models = userAll.ToPaginationList(index, size)
                     .ToList();

            return new PaginationModel { Code = 200, Msg = "success!", Total = total, Result = new { Data = models } };
        }

        /// <summary>
        /// 用户授权
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roId"></param>
        /// <returns></returns>
        public ReturnValueModel UserAuthorization(string userId, string roId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = "用户Id,不能为空!" };
            var userAll = _rep.Where<CrocodileUser>(p => p.Id == userId && p.Status != -1).ToList();
            if (userAll.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "用户查找不到!" };

            var userItem = userAll.FirstOrDefault();
            userItem.RoleId = roId == "undefined" ? string.Empty : roId;
            _rep.Update(userItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        #endregion

        #region 数据字典
        /// <summary>
        /// 数据字典列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetDictionaryAll(int index, int size, string sasearch)
        {
            var dictionaryList = _rep.Where<Dictionary>(p => p.Status == 0);

            var dictionaryAll = dictionaryList.OrderBy(p => p.Level)
                .WhereIf(p => p.Type.Contains(sasearch) || p.Name.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);
            var total = dictionaryAll.Count();

            var models = dictionaryAll.ToPaginationList(index, size)
                     .ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }

        /// <summary>
        /// 数据字典详情
        /// </summary>
        /// <param name="dictionaryId"></param>
        /// <returns></returns>  
        public ReturnValueModel GetDictionary(string dictionaryId)
        {
            if (string.IsNullOrEmpty(dictionaryId))
                return new ReturnValueModel { Code = 400, Msg = "字典Id,不能为空!" };
            var dictionaryList = _rep.Where<Dictionary>(p => p.Status == 0 && p.Id == dictionaryId).ToList();
            if (dictionaryList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var model = dictionaryList.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }

        /// <summary>
        /// 数据字典新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateDictionary(DictionaryModels model)
        {
            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.Type) ? "类型" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Name) ? "名称" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };
            if (string.IsNullOrEmpty(model.Id))
            {
                if (_rep.Where<Dictionary>(p => p.Status == 0 && p.Type == model.Type && p.Name == model.Name).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "字典名称重复!" };

                Dictionary dictionary = new Dictionary()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    Type = model.Type,
                    Name = model.Name,
                    Remarks = model.Remarks
                };
                _rep.Insert(dictionary);

                return new ReturnValueModel { Code = 200, Msg = "success" };
            }

            var dictionaryList = _rep.Where<Dictionary>(p => p.Status == 0 && p.Id == model.Id).ToList();
            if (dictionaryList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该字典,请确认是否为可用状态!" };

            if (_rep.Where<Dictionary>(p => p.Status == 0 && p.Type == model.Type && p.Name == model.Name && p.Id != model.Id).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "字典名称重复!" };

            var dictionaryItem = dictionaryList.FirstOrDefault();
            dictionaryItem.Name = string.IsNullOrEmpty(model.Name) ? dictionaryItem.Name : model.Name;
            dictionaryItem.Type = string.IsNullOrEmpty(model.Type) ? dictionaryItem.Type : model.Type;
            dictionaryItem.Remarks = string.IsNullOrEmpty(model.Remarks) ? dictionaryItem.Remarks : model.Remarks;

            _rep.Update(dictionaryItem);
            return new ReturnValueModel { Code = 200, Msg = "success" };
        }

        /// <summary>
        /// 数据字典删除
        /// </summary>
        /// <param name="dictionaryId"></param>
        /// <returns></returns>
        public ReturnValueModel DelectDictionary(string dictionaryId)
        {
            if (string.IsNullOrEmpty(dictionaryId))
                return new ReturnValueModel { Code = 400, Msg = "字典Id,不能为空!" };
            var dictionaryList = _rep.Where<Dictionary>(p => p.Status == 0 && p.Id == dictionaryId).ToList();
            if (dictionaryList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var dictionaryItem = dictionaryList.FirstOrDefault();
            dictionaryItem.Status = -1;
            _rep.Update(dictionaryItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 数据字典类型列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ReturnValueModel GetDictionaryList(string type)
        {
            var dictionaryAll = _rep.Where<Dictionary>(p => p.Status == 0)
                 .WhereIf(p => p.Type == type, string.IsNullOrEmpty(type) == false)
                 .Select(p => new
                 {
                     p.Id,
                     p.Name,
                     p.Type,
                     p.Level
                 });

            var models = dictionaryAll.OrderBy(p => p.Level).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }
        #endregion

        #region 角色管理
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetRoleAll(int index, int size, string sasearch)
        {
            var roleList = from a in _rep.Where<Role>(p => p.Status == 0)
                           join d in _rep.Where<Dictionary>(p => true) on a.Type equals d.Id
                           select new
                           {
                               a.Id,
                               a.Status,
                               a.Remarks,
                               a.RoleName,
                               a.Details,
                               Type = d.Name
                           };

            var roleAll = roleList.OrderByDescending(p => p.Type)
               .WhereIf(p => p.Type.Contains(sasearch) || p.RoleName.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);
            var total = roleAll.Count();

            var models = roleAll.ToPaginationList(index, size)
                     .ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }
        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ReturnValueModel GetRole(string roleId)
        {
            if (string.IsNullOrEmpty(roleId))
                return new ReturnValueModel { Code = 400, Msg = "角色Id,不能为空!" };
            var roleList = _rep.Where<Role>(p => p.Status == 0 && p.Id == roleId).ToList();
            if (roleList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该角色,请确认是否为可用状态!" };

            var model = roleList.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }
        /// <summary>
        /// 角色新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateRole(RoleModels model)
        {
            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.RoleName) ? "角色名称" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Type) ? "角色类型" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            if (string.IsNullOrEmpty(model.Id))
            {
                if (_rep.Where<Role>(p => p.Status == 0 && p.Type == model.Type && p.RoleName == model.RoleName).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "角色名称重复!" };

                Role role = new Role()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    RoleName = model.RoleName,
                    Type = model.Type,
                    Details = model.Details,
                    Remarks = model.Remarks
                };
                _rep.Insert(role);

                return new ReturnValueModel { Code = 200, Msg = "success!" };
            }

            var roleList = _rep.Where<Role>(p => p.Status == 0 && p.Id == model.Id).ToList();
            if (roleList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该角色,请确认是否为可用状态!" };

            if (_rep.Where<Role>(p => p.Status == 0 && p.Type == model.Type && p.RoleName == model.RoleName && p.Id != model.Id).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "角色名称重复!" };

            var roleItem = roleList.FirstOrDefault();
            roleItem.RoleName = string.IsNullOrEmpty(model.RoleName) ? roleItem.RoleName : model.RoleName;
            roleItem.Type = string.IsNullOrEmpty(model.Type) ? roleItem.Type : model.Type;
            roleItem.Details = string.IsNullOrEmpty(model.Details) ? roleItem.Details : model.Details;
            roleItem.Remarks = string.IsNullOrEmpty(model.Remarks) ? roleItem.Remarks : model.Remarks;

            _rep.Update(roleItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        /// <summary>
        /// 角色停用
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ReturnValueModel DelectRole(string roleId)
        {
            if (string.IsNullOrEmpty(roleId))
                return new ReturnValueModel { Code = 400, Msg = "角色Id,不能为空!" };
            var roleList = _rep.Where<Role>(p => p.Status == 0 && p.Id == roleId).ToList();
            if (roleList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var roleItem = roleList.FirstOrDefault();
            roleItem.Status = -1;
            _rep.Update(roleItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 角色下拉框
        /// </summary>
        /// <returns></returns>
        public ReturnValueModel GetRoleSelect()
        {
            var roleList = from a in _rep.Where<Role>(p => p.Status == 0)
                           join d in _rep.Where<Dictionary>(p => p.Status == 0) on a.Type equals d.Id
                           select new
                           {
                               a.Id,
                               Name = a.RoleName,
                               TypeName = d.Name
                           };

            var models = roleList.OrderBy(p => p.Name).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }
        #endregion

        #region 企业管理
        /// <summary>
        /// 企业列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetEnterpriseAll(int index, int size, string unCode, string sasearch, string enterpriseId)
        {

            //权限数据
            var sql1 = string.Empty;
            List<string> arrt3 = new List<string>();
            string[] arrt4;
            if (!string.IsNullOrEmpty(unCode) && unCode != "undefined" && unCode != "null")
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, unCode).ToList();

                foreach (var item in areaAll)
                    arrt3.Add(item.YUnCode);
                arrt4 = arrt3.ToArray();
            }
            else
            {
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE PUnCode={0} AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, 0).ToList();

                foreach (var item in areaAll)
                    arrt3.Add(item.YUnCode);
                arrt4 = arrt3.ToArray();
            }

            var enterpriseList = from a in _rep.Where<Enterprise>(p => p.Status == 0)
                                 where !string.IsNullOrEmpty(unCode) && unCode != "undefined" && unCode != "null"
                                 ? arrt4.Contains(a.UnCode) : a.Status == 0
                                 join r in _rep.Where<Area>(p => true) on a.UnCode equals r.YUnCode
                                 select new
                                 {
                                     a.Id,
                                     a.EnterpriseName,
                                     a.RegisteredTime,
                                     a.Address,
                                     a.Person,
                                     a.Telephone,
                                     a.Email,
                                     a.Details,
                                     a.Remarks,
                                     a.Status,
                                     a.UnCode,
                                     r.AreaName
                                 };

            var enterpriseAll = enterpriseList.OrderByDescending(p => p.RegisteredTime)
               .WhereIf(p => p.EnterpriseName.Contains(sasearch) || p.Telephone.Contains(sasearch)
               || p.Person.Contains(sasearch) || p.Email.Contains(sasearch),
               string.IsNullOrEmpty(sasearch) == false)
               .WhereIf(p => p.Id == enterpriseId, string.IsNullOrEmpty(enterpriseId) == false);
            var total = enterpriseAll.Count();

            var models = enterpriseAll.ToPaginationList(index, size)
                      .ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }
        /// <summary>
        /// 企业详情列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public PaginationModel GetEnterprisesAll(int index, int size, string id)
        {
            var list = _rep.Where<Enterprises>(p => p.Status == 0 && p.EnterpriseId == id);
            var total = list.Count();
            var models = list.ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }
        /// <summary>
        /// 企业详情
        /// </summary>
        /// <param name="enterpriseId"></param>
        /// <returns></returns>
        public ReturnValueModel GetEnterprise(string enterpriseId)
        {
            if (string.IsNullOrEmpty(enterpriseId))
                return new ReturnValueModel { Code = 400, Msg = "企业Id,不能为空!" };
            var enterpriseList = _rep.Where<Enterprise>(p => p.Status == 0 && p.Id == enterpriseId)
                .Select(p => new EnterpriseModels
                {
                    Id = p.Id,
                    Remarks = p.Remarks,
                    Status = p.Status,
                    UserId = p.UserId,
                    EnterpriseName = p.EnterpriseName,
                    RegisteredTime = p.RegisteredTime,
                    UnCode = p.UnCode,
                    Address = p.Address,
                    Person = p.Person,
                    Telephone = p.Telephone,
                    Email = p.Email,
                    Details = p.Details,
                    LegalPerson = p.LegalPerson,
                    ZipCode = p.ZipCode,
                    XYLicense = p.XYLicense,
                    XYStartDate = p.XYStartDate,
                    XYEndDate = p.XYEndDate,
                    JYLicense = p.JYLicense,
                    JYStartDate = p.JYStartDate,
                    JYEndDate = p.JYEndDate,
                    ApprovedSum = p.ApprovedSum,
                    ApprovedName = p.ApprovedName,
                    ApprovedDepartment = p.ApprovedDepartment
                })
                .ToList();
            if (enterpriseList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该企业,请确认是否为可用状态!" };
            var model = enterpriseList.FirstOrDefault();

            var imageAll = _rep.Where<MediaImage>(p => p.BllId == model.Id).ToList();
            if (imageAll.Count() > 0)
            {
                if (imageAll.Where(p => p.BllType == "企业驯养许可证").Count() > 0)
                    model.XYUrl = string.Format("{0}{1}", UserBasic.Url(), imageAll.Where(p => p.BllType == "企业驯养许可证").FirstOrDefault().FileUrl);

                if (imageAll.Where(p => p.BllType == "企业经营许可证").Count() > 0)
                    model.JYUrl = string.Format("{0}{1}", UserBasic.Url(), imageAll.Where(p => p.BllType == "企业经营许可证").FirstOrDefault().FileUrl);
            }
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }
        /// <summary>
        /// 企业新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateEnterprise(EnterpriseModels model)
        {
            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.EnterpriseName) ? "企业名称" : null));
            mgsList.Add((string.IsNullOrEmpty(model.UnCode) ? "地区" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Address) ? "地址" : null));
            mgsList.Add((string.IsNullOrEmpty(model.LegalPerson) ? "企业法人" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Person) ? "联系人" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Telephone) ? "联系电话" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            if (string.IsNullOrEmpty(model.Id))
            {
                if (_rep.Where<Enterprise>(p => p.Status == 0 && p.EnterpriseName == model.EnterpriseName).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "企业名称已存在!" };

                Enterprise enterprise = new Enterprise()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    EnterpriseName = model.EnterpriseName,
                    RegisteredTime = model.RegisteredTime,
                    UnCode = model.UnCode,
                    Address = model.Address,
                    Person = model.Person,
                    Telephone = model.Telephone,
                    Email = model.Email,
                    LegalPerson = model.LegalPerson,
                    ZipCode = model.ZipCode,
                    XYLicense = model.XYLicense,
                    XYStartDate = model.XYStartDate,
                    XYEndDate = model.XYEndDate,
                    JYLicense = model.JYLicense,
                    JYStartDate = model.JYStartDate,
                    JYEndDate = model.JYEndDate,
                    ApprovedSum = model.ApprovedSum,
                    ApprovedName = model.ApprovedName,
                    ApprovedDepartment = model.ApprovedDepartment,
                    Details = model.Details,
                    Remarks = model.Remarks
                };
                _rep.Insert(enterprise);

                List<Enterprises> enterprisesList = new List<Enterprises>();

                foreach (var item in model.Enterprises)
                {
                    Enterprises items = new Enterprises()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = UserBasic.UserId(),
                        EnterpriseId = enterprise.Id,
                        Name = item.Name,
                        Province = item.Name,
                        City = item.City,
                        Area = item.Area,
                        Address = item.Address
                    };
                    enterprisesList.Add(items);
                }

                if (enterprisesList.Count() > 0)
                    _rep.BulkInsert(enterprisesList);

                return new ReturnValueModel { Code = 200, Msg = "success!" };
            }


            var enterpriseList = _rep.Where<Enterprise>(p => p.Status == 0 && p.Id == model.Id).ToList();
            if (enterpriseList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该企业,请确认是否为可用状态!" };
            if (enterpriseList.Where(p => p.Status == 0 && p.EnterpriseName == model.EnterpriseName && p.Id != model.Id).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "企业名称已存在!" };

            var enterpriseItem = enterpriseList.FirstOrDefault();
            enterpriseItem.EnterpriseName = string.IsNullOrEmpty(model.EnterpriseName) ? enterpriseItem.EnterpriseName : model.EnterpriseName;
            enterpriseItem.RegisteredTime = model.RegisteredTime;
            enterpriseItem.UnCode = string.IsNullOrEmpty(model.UnCode) ? enterpriseItem.UnCode : model.UnCode;
            enterpriseItem.Address = string.IsNullOrEmpty(model.Address) ? enterpriseItem.Address : model.Address;
            enterpriseItem.Person = string.IsNullOrEmpty(model.Person) ? enterpriseItem.Person : model.Person;
            enterpriseItem.Telephone = string.IsNullOrEmpty(model.Telephone) ? enterpriseItem.Telephone : model.Telephone;
            enterpriseItem.Email = string.IsNullOrEmpty(model.Email) ? enterpriseItem.Email : model.Email;
            enterpriseItem.LegalPerson = string.IsNullOrEmpty(model.LegalPerson) ? enterpriseItem.LegalPerson : model.LegalPerson;
            enterpriseItem.ZipCode = string.IsNullOrEmpty(model.ZipCode) ? enterpriseItem.ZipCode : model.ZipCode;
            enterpriseItem.XYLicense = string.IsNullOrEmpty(model.XYLicense) ? enterpriseItem.XYLicense : model.XYLicense;
            if (!string.IsNullOrEmpty(model.XYLicense))
            {
                enterpriseItem.XYStartDate = model.XYStartDate;
                enterpriseItem.XYEndDate = model.XYEndDate;
            }
            enterpriseItem.JYLicense = string.IsNullOrEmpty(model.JYLicense) ? enterpriseItem.JYLicense : model.JYLicense;
            if (!string.IsNullOrEmpty(model.JYLicense))
            {
                enterpriseItem.JYStartDate = model.JYStartDate;
                enterpriseItem.JYEndDate = model.JYEndDate;
            }
            enterpriseItem.ApprovedSum = model.ApprovedSum;
            enterpriseItem.ApprovedName = string.IsNullOrEmpty(model.ApprovedName) ? enterpriseItem.ApprovedName : model.ApprovedName;
            enterpriseItem.ApprovedDepartment = string.IsNullOrEmpty(model.ApprovedDepartment) ? enterpriseItem.ApprovedDepartment : model.ApprovedDepartment;
            enterpriseItem.Details = string.IsNullOrEmpty(model.Details) ? enterpriseItem.Details : model.Details;
            enterpriseItem.Remarks = string.IsNullOrEmpty(model.Remarks) ? enterpriseItem.Remarks : model.Remarks;

            _rep.Update(enterpriseItem);

            List<Enterprises> enterprisesAll = new List<Enterprises>();

            foreach (var item in model.Enterprises)
            {
                Enterprises items = new Enterprises()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    EnterpriseId = model.Id,
                    Name = item.Name,
                    Province = item.Name,
                    City = item.City,
                    Area = item.Area,
                    Address = item.Address
                };
                enterprisesAll.Add(items);
            }

            if (enterprisesAll.Count() > 0)
            {
                var list = _rep.Where<Enterprises>(p => p.EnterpriseId == model.Id).ToList();
                _rep.RemoveRange(list);
                _rep.BulkInsert(enterprisesAll);
            }

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        /// <summary>
        /// 企业停用
        /// </summary>
        /// <param name="enterpriseId"></param>
        /// <returns></returns>
        public ReturnValueModel DelectEnterprise(string enterpriseId)
        {
            if (string.IsNullOrEmpty(enterpriseId))
                return new ReturnValueModel { Code = 400, Msg = "企业Id,不能为空!" };
            var enterpriseList = _rep.Where<Enterprise>(p => p.Status == 0 && p.Id == enterpriseId).ToList();
            if (enterpriseList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var enterpriseItem = enterpriseList.FirstOrDefault();
            enterpriseItem.Status = -1;
            _rep.Update(enterpriseItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 企业选择列表
        /// </summary>
        /// <param name="areCode"></param>
        /// <returns></returns>
        public ReturnValueModel GetEnterpriseTree(string areCode)
        {
            if (string.IsNullOrEmpty(areCode) || areCode == "undefined" || areCode == "null")
            {
                var list = _rep.Where<Enterprise>(p => p.Status == 0)
                               .Select(p => new { p.Id, Name = p.EnterpriseName }).ToList();

                return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = list } };
            }
            else
            {
                var sql1 = string.Empty;
                List<string> arrt3 = new List<string>();
                string[] arrt4;
                sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAll = _rep.SqlQuery<Area>(sql1, areCode).ToList();
                foreach (var item in areaAll)
                    arrt3.Add(item.YUnCode);
                arrt4 = arrt3.ToArray();

                var list = from a in _rep.Where<Enterprise>(p => p.Status == 0)
                           where arrt4.Contains(a.UnCode)
                           select new
                           {
                               a.Id,
                               Name = a.EnterpriseName
                           };

                var models = list.ToList();
                return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
            }
        }

        /// <summary>
        /// 企业媒体文件上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateEnterPriseImage(MediaImageModels model)
        {
            var enpImageList = _rep.Where<MediaImage>(p => p.BllId == model.BllId && p.BllType == model.BllType).ToList();
            if (enpImageList.Count() > 0)
                _rep.RemoveRange(enpImageList);

            MediaImage mediaImage = new MediaImage()
            {
                Id = Guid.NewGuid().ToString(),
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = UserBasic.UserId(),
                BllId = model.BllId,
                BllType = model.BllType,
                FileUrl = model.FileUrl,
                Type = model.Type,
            };

            _rep.Insert(mediaImage);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 企业宣传资料上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddEnterPrisePropaganda(MediaImageModels model)
        {
            MediaImage mediaImage = new MediaImage()
            {
                Id = Guid.NewGuid().ToString(),
                Status = 0,
                CreateTime = DateTime.Now,
                CreateId = UserBasic.UserId(),
                BllId = model.BllId,
                BllType = model.BllType,
                FileUrl = model.FileUrl,
                Type = model.Type,
            };

            _rep.Insert(mediaImage);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 企业宣传资料查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValueModel GetEnterPrisePropagandaAll(string id)
        {
            var list = _rep.Where<MediaImage>(p => p.BllId == id && p.BllType == "企业宣传").Select(p => new
            {
                p.Id,
                p.Type,
                p.BllType,
                FileUrl = string.Format("{0}{1}", UserBasic.Url(), p.FileUrl)
            });

            var models = list.ToList();
            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = models } };
        }
        /// <summary>
        /// 企业宣传资料删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValueModel DeleteEnterPrisePropaganda(string id)
        {
            var itemAll = _rep.Where<MediaImage>(p => p.Id == id);

            if (itemAll.Count() > 0)
                _rep.RemoveRange(itemAll);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        #endregion

        #region 地区管理
        /// <summary>
        /// 地区树
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public object GetAreaTreeAll(string name)
        {
            if (!string.IsNullOrEmpty(name) && name != "undefined" && name != "null")
            {
                var allMenuList = _rep.Where<Area>(p => p.Status == 0).OrderBy(p => p.YUnCode).ToList();
                List<TreeModel> rootNodeList = new List<TreeModel>();
                foreach (var parentNodeList in allMenuList.Where(p => p.YUnCode == name))
                {
                    TreeModel menuNode = new TreeModel();
                    menuNode.id = parentNodeList.YUnCode;
                    menuNode.name = parentNodeList.AreaName;
                    menuNode.open = "true";
                    menuNode.children = CreateChildTree(allMenuList, menuNode.id);
                    rootNodeList.Add(menuNode);
                }
                return rootNodeList;
            }
            else
            {
                var allMenuList = _rep.Where<Area>(p => p.Status == 0).OrderBy(p => p.YUnCode).ToList();
                List<TreeModel> rootNodeList = new List<TreeModel>();
                foreach (var parentNodeList in allMenuList.Where(t => t.PUnCode == "0"))
                {
                    TreeModel menuNode = new TreeModel();
                    menuNode.id = parentNodeList.YUnCode;
                    menuNode.name = parentNodeList.AreaName;
                    menuNode.open = "false";
                    menuNode.children = CreateChildTree(allMenuList, menuNode.id);
                    rootNodeList.Add(menuNode);
                }
                return rootNodeList;
            }
        }

        /// <summary>
        /// 递归生成子树
        /// </summary>
        /// <param name="AllMenuList"></param>
        /// <param name="vmMenu"></param>
        /// <returns></returns>
        private List<TreeModel> CreateChildTree(List<Area> AllMenuList, string id)
        {
            // string parentMenuID = vmMenu.id;//根节点ID
            List<TreeModel> nodeList = new List<TreeModel>();
            var children = AllMenuList.Where(t => t.PUnCode == id);
            foreach (var chl in children)
            {
                TreeModel node = new TreeModel();
                node.id = chl.YUnCode;
                node.name = chl.AreaName;
                node.open = "false";
                node.children = CreateChildTree(AllMenuList, node.id);
                nodeList.Add(node);
            }
            return nodeList;
        }

        /// <summary>
        /// 地区列表
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public PaginationModel GetAreaAll(string code)
        {
            List<Area> areaAll = new List<Area>();
            if (string.IsNullOrEmpty(code) || code == "null")
            {
                areaAll = _rep.Where<Area>(p => p.Status == 0).ToList();
            }
            else
            {
                var sql1 = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} AND Status=0 UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                areaAll = _rep.SqlQuery<Area>(sql1, code).ToList();
            }

            return new PaginationModel { Code = 200, Msg = "success!", Result = new { Data = areaAll } };
        }

        /// <summary>
        /// 省市区联动
        /// </summary>
        /// <param name="lev"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ReturnValueModel GetAreaSelectAll(int lev, string name)
        {
            var arelist = _rep.Where<Area>(p => p.Status == 0 && p.Level == 1)
                .Select(p => new { p.Id, p.Level, p.YUnCode, name = p.AreaName }).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = arelist } };
        }
        #endregion

        #region 产品管理
        /// <summary>
        /// 产品列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetSpeciesManageAll(int index, int size, string sasearch)
        {
            var roleList = from a in _rep.Where<SpeciesManage>(p => p.Status == 0)
                           join d in _rep.Where<Dictionary>(p => true) on a.Type equals d.Id
                           select new
                           {
                               a.Id,
                               a.Status,
                               a.Remarks,
                               a.SpeciesName,
                               a.Details,
                               Type = d.Name
                           };

            var roleAll = roleList.OrderByDescending(p => p.Type)
               .WhereIf(p => p.Type.Contains(sasearch) || p.SpeciesName.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);
            var total = roleAll.Count();

            var models = roleAll.ToPaginationList(index, size)
                     .ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };
        }
        /// <summary>
        /// 产品详情
        /// </summary>
        /// <param name="speciesId"></param>
        /// <returns></returns>
        public ReturnValueModel GetSpeciesManage(string speciesId)
        {
            if (string.IsNullOrEmpty(speciesId))
                return new ReturnValueModel { Code = 400, Msg = "产品Id,不能为空!" };
            var enterpriseList = _rep.Where<SpeciesManage>(p => p.Status == 0 && p.Id == speciesId).ToList();
            if (enterpriseList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该产品,请确认是否为可用状态!" };

            var model = enterpriseList.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }
        /// <summary>
        /// 产品新增修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateSpeciesManage(SpeciesManageModels model)
        {

            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.SpeciesName) ? "产品名称" : null));
            mgsList.Add((string.IsNullOrEmpty(model.Type) ? "产品类型" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            if (string.IsNullOrEmpty(model.Id))
            {
                if (_rep.Where<SpeciesManage>(p => p.Status == 0 && p.Type == model.Type && p.SpeciesName == model.SpeciesName).Count() > 0)
                    return new ReturnValueModel { Code = 400, Msg = "产品名称重复!" };

                SpeciesManage speciesManage = new SpeciesManage()
                {
                    Id = Guid.NewGuid().ToString(),
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = UserBasic.UserId(),
                    SpeciesName = model.SpeciesName,
                    Type = model.Type,
                    Details = model.Details,
                    Remarks = model.Remarks
                };
                _rep.Insert(speciesManage);

                return new ReturnValueModel { Code = 200, Msg = "success!" };
            }

            var roleList = _rep.Where<SpeciesManage>(p => p.Status == 0 && p.Id == model.Id).ToList();
            if (roleList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该产品,请确认是否为可用状态!" };

            if (_rep.Where<SpeciesManage>(p => p.Status == 0 && p.Type == model.Type && p.SpeciesName == model.SpeciesName && p.Id != model.Id).Count() > 0)
                return new ReturnValueModel { Code = 400, Msg = "产品名称重复!" };

            var roleItem = roleList.FirstOrDefault();
            roleItem.SpeciesName = string.IsNullOrEmpty(model.SpeciesName) ? roleItem.SpeciesName : model.SpeciesName;
            roleItem.Type = string.IsNullOrEmpty(model.Type) ? roleItem.Type : model.Type;
            roleItem.Details = string.IsNullOrEmpty(model.Details) ? roleItem.Details : model.Details;
            roleItem.Remarks = string.IsNullOrEmpty(model.Remarks) ? roleItem.Remarks : model.Remarks;

            _rep.Update(roleItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        /// <summary>
        /// 产品删除
        /// </summary>
        /// <param name="speciesId"></param>
        /// <returns></returns>
        public ReturnValueModel DelectSpeciesManage(string speciesId)
        {
            if (string.IsNullOrEmpty(speciesId))
                return new ReturnValueModel { Code = 400, Msg = "产品Id,不能为空!" };
            var roleList = _rep.Where<SpeciesManage>(p => p.Status == 0 && p.Id == speciesId).ToList();
            if (roleList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var roleItem = roleList.FirstOrDefault();
            roleItem.Status = -1;
            _rep.Update(roleItem);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        /// 产品选择列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ReturnValueModel GetSpeciesManageTree(string type)
        {
            var list = _rep.Where<SpeciesManage>(p => p.Type == type)
                 .Select(p => new { p.Id, p.Type, Name = p.SpeciesName, p.Level }).OrderBy(p => p.Level).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = list } };
        }
        #endregion

        #region 系统菜单
        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationModel GetMenuAll(int index, int size, string sasearch)
        {
            var menuList = _rep.Where<Menu>(p => p.Status == 0);

            var menuAll = menuList.OrderBy(p => p.Sql)
              .WhereIf(p => p.MenuName.Contains(sasearch) || p.MuCode.Contains(sasearch), string.IsNullOrEmpty(sasearch) == false);

            var total = menuAll.Count();

            var models = menuAll.ToPaginationList(index, size)
                     .ToList();
            return new PaginationModel { Code = 200, Msg = "success", Total = total, Result = new { Data = models } };

        }
        /// <summary>
        /// 菜单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValueModel GetMenu(string id)
        {
            if (string.IsNullOrEmpty(id))
                return new ReturnValueModel { Code = 400, Msg = "菜单Id,不能为空!" };
            var menuList = _rep.Where<Menu>(p => p.Status == 0 && p.Id == id).ToList();
            if (menuList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该菜单,请确认是否为可用状态!" };

            var model = menuList.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = model } };
        }
        /// <summary>
        /// 菜单新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateMenuAll(MenuModels model)
        {

            List<string> mgsList = new List<string>();
            mgsList.Add((string.IsNullOrEmpty(model.MenuName) ? "菜单名称" : null));
            mgsList.Add((string.IsNullOrEmpty(model.MuCode) ? "菜单编码" : null));
            foreach (var item in mgsList)
                if (!string.IsNullOrEmpty(item))
                    return new ReturnValueModel { Code = 400, Msg = String.Format("您的{0}没有填写!", item) };

            Menu menu = new Menu()
            {
                Id = Guid.NewGuid().ToString(),
                Status = 0,
                CreateId = UserBasic.UserId(),
                CreateTime = DateTime.Now,
                SuperionMenuId = model.SuperionMenuId,
                Sql = model.Sql,
                MenuName = model.MenuName,
                MuCode = model.MuCode
            };

            _rep.Insert(menu);
            return new ReturnValueModel { Code = 200, Msg = "success!" };

        }
        /// <summary>
        /// 菜单删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReturnValueModel DeleteMenu(string id)
        {
            if (string.IsNullOrEmpty(id))
                return new ReturnValueModel { Code = 400, Msg = "菜单Id,不能为空!" };
            var menuList = _rep.Where<SpeciesManage>(p => p.Status == 0 && p.Id == id).ToList();
            if (menuList.Count() == 0)
                return new ReturnValueModel { Code = 404, Msg = "查找不到该详情,请确认是否为可用状态!" };

            var menuItem = menuList.FirstOrDefault();
            menuItem.Status = -1;
            _rep.Update(menuItem);
            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }
        /// <summary>
        /// 菜单树
        /// </summary>
        /// <returns></returns>
        public PaginationyMenuModel MenuTree()
        {
            var MenuList = _rep.Where<Menu>(p => p.Status == 0).Select(p => new { p.Id, p.MenuName, p.SuperionMenuId }).ToList();

            List<MenuTreeModel> list = new List<MenuTreeModel>();
            foreach (var parentNodeList in MenuList)
            {
                MenuTreeModel menuNode = new MenuTreeModel();
                menuNode.id = parentNodeList.Id;
                menuNode.name = parentNodeList.MenuName;
                menuNode.pid = parentNodeList.SuperionMenuId;
                list.Add(menuNode);
            }
            return new PaginationyMenuModel { code = 0, msg = "success", data = new { list } };
        }
        /// <summary>
        /// 菜单下拉列表
        /// </summary>
        /// <returns></returns>
        public ReturnValueModel MenuSelect()
        {
            var list = _rep.Where<Menu>(p => p.Status == 0 && p.Sql == 1).OrderBy(p => p.CreateTime)
                .Select(p => new { p.Id, p.MuCode, Name = p.MenuName, p.Sql }).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success!", Result = new { Data = list } };
        }

        /// <summary>
        /// 角色授权菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnValueModel AddUpdateRoleMenu(UpdateRoleMenu model)
        {
            if (string.IsNullOrEmpty(model.RoleId))
                return new ReturnValueModel { Code = 400, Msg = "角色Id不能为空!" };

            var menuAll = _rep.Where<RoleMenu>(p => p.Status == 0 && p.RoleId == model.RoleId).ToList();
            if (menuAll.Count() > 0)
                _rep.RemoveRange(menuAll);

            List<RoleMenu> roleList = new List<RoleMenu>();
            foreach (var itme in model.ListMenuId)
            {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.Id = Guid.NewGuid().ToString();
                roleMenu.RoleId = model.RoleId;
                roleMenu.MenuId = itme;
                roleMenu.CreateTime = DateTime.Now;
                roleMenu.Status = 0;
                roleMenu.CreateId = "740f890c-01c7-11ea-9b2b-5cf3fc26ebaa";

                roleList.Add(roleMenu);
            }
            if (roleList.Count() > 0)
                _rep.BulkInsert(roleList);

            return new ReturnValueModel { Code = 200, Msg = "success!" };
        }

        /// <summary>
        ///  角色菜单列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public PaginationyMenuModel GetRoleMenu(string roleid)
        {

            if (string.IsNullOrEmpty(roleid))
                return null;

            var checkedIdList = from a in _rep.Where<RoleMenu>(p => p.RoleId == roleid)
                                join m in _rep.Where<Menu>(p => true) on a.MenuId equals m.Id
                                select new
                                {
                                    id = m.Id,
                                    name = m.MenuName,
                                    pid = m.SuperionMenuId.Trim()
                                };
            List<string> checkedId = new List<string>();
            foreach (var item in checkedIdList.ToList())
                checkedId.Add(item.id);
            var MenuList = _rep.Where<Menu>(p => true).Select(p => new { p.Id, p.MenuName, p.SuperionMenuId }).ToList();

            List<MenuTreeModel> list = new List<MenuTreeModel>();
            foreach (var parentNodeList in MenuList)
            {
                MenuTreeModel menuNode = new MenuTreeModel();
                menuNode.id = parentNodeList.Id;
                menuNode.name = parentNodeList.MenuName;
                menuNode.pid = parentNodeList.SuperionMenuId;
                list.Add(menuNode);
            }
            return new PaginationyMenuModel { code = 0, msg = "success", data = new { list, checkedId } };
        }
        #endregion
    }

}
